<template>
    <div class="weiMusicContent">
        <audio ref="audioRefPlay" controls style="opacity: 0;position: absolute;" preload="auto" @timeupdate="updateProgress" @ended="next">
            <source :src="audioSrc" type="audio/mp3">
            Your browser does not support the audio element.
        </audio>
        <div class="goBack" @click="goBack">
            <van-icon name="arrow-left" size="30" color="#a49144" />
        </div>
        <div class="albumCover">
            <div class="imgBox" :class="{ rotating: isPlaying }">
                <img :src="imgSrc" alt="" v-if="imgSrc">
                <div class="imgBoxItem"></div>
            </div>
        </div>
        <div class="albumName">
            <p>{{ audioTitle || '--' }}</p>
            <p>{{ author || '--' }}</p>
        </div>
        <div class="ControlsBox">
            <div class="ControlsRange">
                <span class="ControlsRangeTime">{{ songBeginTime || '0.00' }}</span>
                <input type="range" min="0" :max="duration" id="myRange" v-model="currentTime" @change="setProgress">
                <span class="ControlsRangeTime">{{ songAllTime || '-' }}</span>
            </div>
            <div class="ControlsBoxItem">
                <div class="playBtn" @click="previous">
                    <SvgIcon width="40px" height="40px" name="previousSong" color="#a49144"></SvgIcon>
                </div>
                <div class="playBtn" @click="pause" v-if="isPlaying">
                    <SvgIcon width="50px" height="50px" name="play" color="#a49144"></SvgIcon>
                </div>
                <div class="playBtn" @click="play" v-else>
                    <SvgIcon width="50px" height="50px" name="pause" color="#a49144"></SvgIcon>
                </div>
                <div class="playBtn" @click="next">
                    <SvgIcon width="40px" height="40px" name="nextSong" color="#a49144"></SvgIcon>
                </div>
            </div>
        </div>
    </div>
</template>
    
<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, computed, onUnmounted, watchEffect } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { sourceHeader } from '@/utils/plugins'
import { showToast, showFailToast } from 'vant'
import useSettingStore from '@/store/modules/setting'
import musicStore from '@/store/modules/musicDataList'
const settings = useSettingStore()
const musicStoreList = musicStore()


const route = useRoute()
const router = useRouter()

const audioRefPlay = ref<any>(null)
const duration = ref<any>(0);
const currentTime = ref<any>(0);


const musicList = ref<any>([])
const audioSrc = ref<any>(null) // 当前播放
const imgSrc = ref<any>(null) // 当前播放
const audioTitle = ref<any>('') // 当前播放
const author = ref<any>('') // 当前播放
const songBeginTime = ref<any>('') // 当前播放
const songAllTime = ref<any>('') // 当前播放
const isPlaying = ref<any>(true)

const play = () => {
    if (audioRefPlay.value) {
        if (audioSrc.value) {
            isPlaying.value = true
            console.log('audioSrc:', audioSrc.value)
            audioRefPlay.value.play().catch(error => {
                console.error('Error playing audio:', error);
                pause()
                return
            })
        } else {
            return
        } 
    }
}

const pause = () => {
    isPlaying.value = false
    console.log(isPlaying.value)
    audioRefPlay.value.pause()
}

const previous = () => {
    const index = musicList.value.findIndex(item => item.song === audioSrc.value)
    if (index > 0) {
        audioSrc.value = musicList.value[index - 1].song
        imgSrc.value = musicList.value[index - 1].img
        audioTitle.value = musicList.value[index - 1].title
        author.value = musicList.value[index - 1].author
        audioRefPlay.value.load(); // 确保重新加载音频数据
        // play()
    } else {
        showToast('已经是第一首了')
    }
}

const next = () => {
    const index = musicList.value.findIndex(item => item.song === audioSrc.value)
    if (index < musicList.value.length - 1) {
        audioSrc.value = musicList.value[index + 1].song
        imgSrc.value = musicList.value[index + 1].img
        audioTitle.value = musicList.value[index + 1].title
        author.value = musicList.value[index + 1].author
        audioRefPlay.value.load(); // 确保重新加载音频数据
        // play()
    } else {
        showToast('已经是最后一首了')
    }
}

const updateProgress = () => {
    if (audioRefPlay.value) {
        currentTime.value = audioRefPlay.value.currentTime;
        if (currentTime.value) {
            songBeginTime.value = formatDuration(currentTime.value)
        }
    }
}

const setProgress = () => {
    if (currentTime.value) {
        audioRefPlay.value.currentTime = currentTime.value;
    }
}

const formatDuration = (duration) => {
    const minutes = Math.floor(duration / 60);
    const seconds = Math.floor(duration % 60);
    return `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`; // 确保秒是两位数
}

watchEffect(() => {
    if (audioRefPlay.value) {
        settings.handlerLoadingShow(true)
        audioRefPlay.value.src = audioSrc.value
        audioRefPlay.value.load(); // 确保重新加载音频数据
        settings.handlerLoadingShow(false)
    }
})

const goBack = () => {
    router.go(-1)
}


onMounted(() => {
    settings.handlerLoadingShow(true)
    settings.handlerHeaderShow(false)
    if (musicStoreList.musicDataList && musicStoreList.musicDataList.length) {
        musicList.value = musicStoreList.musicDataList
        if (musicStoreList.musicItemDataList && musicStoreList.musicItemDataList.length > 0) {
            settings.handlerLoadingShow(false)
            let index = musicList.value.findIndex((item: any) => item.id == musicStoreList.musicItemDataList[0].id)
            audioSrc.value = musicList.value[index].song
            imgSrc.value = musicList.value[index].img
            audioTitle.value = musicList.value[index].title
            author.value = musicList.value[index].author
        } else {
            settings.handlerLoadingShow(false)
            audioSrc.value = musicList.value[0].song
            imgSrc.value = musicList.value[0].img
            audioTitle.value = musicList.value[0].title
            author.value = musicList.value[0].author
        }
    }
    audioRefPlay.value.addEventListener('loadedmetadata', () => {
        duration.value = audioRefPlay.value.duration;
        if (duration.value) {
            songAllTime.value = formatDuration(duration.value)
            play()
        }
    });
});

onBeforeUnmount(() => {
    if (audioRefPlay.value) {
        audioRefPlay.value.removeEventListener('loadedmetadata', () => {});
    }
    settings.handlerHeaderShow(true)
});

</script>


<style lang="scss" scoped>
.weiMusicContent {
    width: 100%;
    height: 100vh;
    background-color: #222222;
    position: relative;
    // padding: 15px;
    overflow: hidden;
    .goBack {
        position: absolute;
        left: 20px;
        top: 20px;
    }
    .albumCover {
        width: 100%;
        height: 60%;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        .imgBox {
            width: 65%;
            height: auto;
            border-radius: 50%;
            aspect-ratio: 1;
            overflow: hidden;
            border: 3px solid #383837;
            position: relative;
            transition: transform 2s linear; /* 平滑旋转 */
            img {
                width: 100%;
                height: 100%;
                object-fit: cover;
            }
            .imgBoxItem {
                width: 50px;
                height: 50px;
                border-radius: 50%;
                background-color: #383837;
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
            }
        }
        .rotating {
            animation: rotate 12s linear infinite; /* 无限循环旋转 */
        }
        @keyframes rotate {
            from {
                transform: rotate(0deg);
            }
            to {
                transform: rotate(360deg);
            }
        }
    }
    .albumName {
        width: 100%;
        height: 30px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        p {
            text-align: center;
            font-size: 16px;
            color: #919191;
        }
        :last-child {
            font-size: 12px;
            margin-top: 5px;
        }
    }
    .ControlsBox {
        width: 100%;
        // height: 40%;
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        .ControlsRange {
            width: 100%;
            padding: 0 25px;
            margin-top: 50px;
            margin-bottom: 30px;
            display: flex;
            flex-direction: row;
            align-items: center;
            input[type="range"] {
                width: 100%; /* 或者其他宽度 */
                -webkit-appearance: none; /* 移除默认样式 */
                border-radius: 10px;
                // box-shadow: 0 1px 1px #def3f8, inset 0 .125em .125em #0d1112; /*轨道内置阴影效果*/
                height: 1px; /* 指定滑块的高度 */
                background: #a49144; /* 滑块背景颜色 */
                outline: none; /* 移除轮廓 */
                opacity: 0.7; /* 设置透明度 */
                -webkit-transition: .2s; /* 过渡效果 */
                transition: opacity .2s; /* 过渡效果 */
            }
            #myRange::-webkit-slider-thumb {
                -webkit-appearance: none; /* 移除默认样式 */
                background: #a49144; /* 红色把手 */
                width: 15px; /* 设置把手的大小 */
                height: 15px; /* 设置把手的大小 */
                border-radius: 50%; /* 圆形把手 */
            }
            .ControlsRangeTime {
                color: #919191;
            }
        }
        .ControlsBoxItem {
            width: 100%;
            height: 80px;
            display: flex;
            flex-direction: row;
            justify-content: space-evenly;
            align-items: center;
            .playBtn {
                
            }
        }
    }
}
</style>